import React from 'react';

import { Modal, Form, Input, Tooltip, Select, AutoComplete, notification as Notification } from 'antd';

import { FormInstance } from 'antd/lib/form';
import PropTypes from 'prop-types';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { saveUser, updateUser } from '../../../../api/user';

class UserForm extends React.Component {
  state = {
    visible: false,
    type: 'add',
    user: {},
    autoCompleteResult: [],
  };

  formRef = React.createRef(FormInstance);

  constructor(props) {
    super(props);
    const { visible, user, type } = props;
    this.state = {
      visible,
      user,
      type,
      autoCompleteResult: []
    };
  }

  UNSAFE_componentWillReceiveProps(nextProps, nextContext) {
    const state = Object.assign(this.state, JSON.parse(JSON.stringify(nextProps)));
    this.setState(state);
  }

  onClose = () => {
    const { onClose } = this.props;
    if (typeof onClose === 'function') {
      onClose();
    }
  };

  saveOrUpdate = () => {
    const form = this.formRef.current;
    const { type, user } = this.state;

    form.validateFields().then((values) => {
      if (type === 'add') {
        saveUser(values).then(({ data }) => {
          Notification.success({
            message: `添加 ${data.username} 成功`,
            duration: 2
          });
          this.onClose();
        }).catch((e) => {
          console.log(e, typeof e, 'e');
        });
      } else if (type === 'edit') {
        Object.assign(user, values);
        updateUser(user).then(({ data }) => {
          Notification.success({
            message: `更新${data.username}成功`,
            duration: 2
          });
          this.onClose();
        }).catch((e) => {
          console.log(e, typeof e, 'e');
        });
      }
    }).catch((errorInfo) => {
      const { errorFields } = errorInfo;
      Notification.error({
        message: errorFields[0].errors[0],
        duration: 2
      });
    });
  };

  render() {
    const { visible, type, user, autoCompleteResult } = this.state;
    const { onClose } = this.props;

    const disabled = type === 'detail';
    const initialValues = type === 'add' ? {} : user;

    const titleMapping = {
      add: '新增用户',
      edit: '修改用户',
      detail: '用户详情',
    };

    const onFinish = (values) => {
      console.log('Received values of form: ', values);
    };

    const setAutoCompleteResult = (value) => {
      this.setState({
        autoCompleteResult: value
      });
    };

    const onEmailChange = (value) => {
      if (!value) {
        setAutoCompleteResult([]);
      } else {
        const emailSuffix = ['@126.com', '@163.com', '@163.com ', '@163.net', '@21cn.com ', '@gmail.com', '@qq.com', '@sina.com', '@sohu.com ', '@yahoo.com'];
        const emailGuess = emailSuffix.map((domain) => `${value.replace(/(.*)(@.*)/, '$1')}${domain}`);
        const autoComplete = emailGuess.filter((i) => i.startsWith(value));
        setAutoCompleteResult(autoComplete);
      }
    };

    const emailOptions = autoCompleteResult.map((email) => ({
      label: email,
      value: email,
    }));

    return (
      <Modal
        visible={visible}
        destroyOnClose
        title={titleMapping[type] || '新增'}
        okText="确定"
        cancelText="取消"
        onCancel={() => {onClose();}}
        onOk={this.saveOrUpdate}
        maskClosable={false}
      >
        <Form
          ref={this.formRef}
          {
            ...{
              labelCol: { span: 4 },
              wrapperCol: { span: 20 },
            }
          }
          name="userForm"
          onFinish={onFinish}
          initialValues={{ ...initialValues }}
          scrollToFirstError
        >
          <Form.Item
            name="account"
            label={
              <span>学号&nbsp;
                <Tooltip title="唯一的编号">
                  <QuestionCircleOutlined/>
                </Tooltip>
              </span>
            }
            rules={[
              {
                required: true,
                message: '请输入学号!',
                whitespace: true
              },
            ]}
            hasFeedback
          >
            <Input disabled={disabled}/>
          </Form.Item>
          <Form.Item
            name="username"
            label="姓名"
            rules={[{ required: true, message: '请输入姓名!', whitespace: true }]}
            hasFeedback
          >
            <Input/>
          </Form.Item>
          <Form.Item name="sex" label="性别" initialValue="1">
            <Select>
              <Select.Option value="1">男</Select.Option>
              <Select.Option value="0">女</Select.Option>
              <Select.Option value="2">保密</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item
            name="password"
            label="密码"
            rules={[
              {
                required: true,
                message: '请输入密码!',
                whitespace: true
              },
            ]}
            hidden={disabled}
            initialValue="123456"
            hasFeedback
          >
            <Input.Password/>
          </Form.Item>

          <Form.Item
            name="repassword"
            label="确认密码"
            dependencies={['password']}
            hasFeedback
            hidden={disabled}
            initialValue="123456"
            rules={[
              {
                required: true,
                message: '请再次输入密码!',
              },
              ({ getFieldValue }) => ({
                validator(rule, value) {
                  if (!value || getFieldValue('password') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject('两次密码不一致!');
                },
              }),
            ]}
          >
            <Input.Password/>
          </Form.Item>

          <Form.Item
            name="phone"
            label="手机号"
            rules={[{ required: true, message: '请输入手机号!', whitespace: true }]}
            hasFeedback
          >
            <Input style={{ width: '100%' }} disabled={disabled}/>
          </Form.Item>

          <Form.Item
            name="email"
            label="邮箱"
            rules={[
              {
                type: 'email',
                message: '请输入正确邮箱格式!',
              },
              {
                required: true,
                message: '请输入邮箱号!',
                whitespace: true
              },
            ]}
            hasFeedback
            validateTrigger="onBlur"
          >
            <AutoComplete options={emailOptions} onChange={onEmailChange} placeholder="邮箱">
              <Input disabled={disabled}/>
            </AutoComplete>
          </Form.Item>
          <Form.Item name='remark' label="备注">
            <Input.TextArea />
          </Form.Item>
        </Form>
      </Modal>
    );
  }
}

UserForm.propTypes = {
  // push: PropTypes.bool,
  // from: PropTypes.string,
  // to: PropTypes.oneOfType([PropTypes.string, PropTypes.object]).isRequired
  visible: PropTypes.bool.isRequired,
  type: PropTypes.string.isRequired,
  user: PropTypes.object,
  onClose: PropTypes.func.isRequired
};

export default UserForm;
